package org.geektimes.web.mvc.servlet;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.geektimes.configuration.microprofile.config.DefaultConfigProviderResolver;
import org.geektimes.configuration.microprofile.config.source.ServletContextConfigSource;
import org.geektimes.configuration.microprofile.config.source.servlet.MyConfigurationListener;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

/**
 * @author :   chuan
 * @date :   2021/03/23
 */
public class MyConfigurationInitializer implements MyWebMvcInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
//        servletContext.addListener(MyConfigurationListener.class);

        servletContext.setInitParameter("servletInitParameterKey", "servletInitParameterValue");
        servletContext.setInitParameter("homeworkKey", "homeworkValue");

        ClassLoader classLoader = servletContext.getClassLoader();

        ServletContextConfigSource servletContextConfigSource = new ServletContextConfigSource(servletContext);

        DefaultConfigProviderResolver configProviderResolver = new DefaultConfigProviderResolver();
        ConfigBuilder configBuilder = configProviderResolver.getBuilder();

        configBuilder.forClassLoader(classLoader);

        configBuilder.addDefaultSources();
        configBuilder.addDiscoveredSources();
        configBuilder.withSources(servletContextConfigSource);

        configBuilder.addDiscoveredConverters();

        Config config = configBuilder.build();

        configProviderResolver.registerConfig(config, classLoader);

        Config resolverConfig = configProviderResolver.getConfig(classLoader);

        servletContext.setAttribute("applicationConfig", resolverConfig);

        System.out.println(this.getClass().getSimpleName() +
                "--------Load Success-------->: servletInitParameterKey = " +
                resolverConfig.getValue("servletInitParameterKey", String.class));
    }
}
